package com.qdaily.ui.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.util.*;
import com.qdaily.ui.QDBaseActivity;
import com.qdaily.ui.R;
import com.qdaily.ui.data.DataBase.PraiseDAO;
import com.qdaily.ui.data.DataBase.ReadDAO;
import com.qdaily.ui.data.EventModel.EventAddNewMob;
import com.qdaily.ui.data.UserInformationManager;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.net.entity.LikeItEntity;
import com.qdaily.ui.net.entity.MobOptionsEntity;
import com.qdaily.ui.net.entity.QuestionDetailsEntity;
import com.qdaily.ui.net.model.ArticleInfoShare;
import com.qdaily.ui.net.model.ArticleMeta;
import com.qdaily.ui.ui.adapter.MobListAdapter;
import com.qdaily.ui.ui.views.OnRefreshAndLoadMoreListener;
import com.qdaily.ui.ui.views.QDRefreshListView;
import com.qdaily.ui.ui.views.ShareDialog;
import com.qdaily.ui.ui.views.TitleBar;
import com.squareup.otto.Subscribe;

/**
 * MOB详情页
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/10/15
 * Time: 14:55
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class VotingMobDetailsActivity extends QDBaseActivity implements View.OnClickListener, MobListAdapter.OnMobClickListener, OnRefreshAndLoadMoreListener {
    public final static String KEY_REQUEST_VOTING_DETAILS = "VotingMobDetailsActivity-REQUEST_VOTING_DETAILS_KEY";
    public final static String KEY_REQUEST_MOB_ID = "KEY_REQUEST_MOB_ID";
    private ArticleMeta articleMeta;
    private QuestionDetailsEntity questionDetailsEntity;
    private MobOptionsEntity mobOptionsEntity;

    //top show
    private TitleBar viewTitleHeaderBar;
    private View headerView = null;
    private RelativeLayout relativeLayoutResearchListViewItemContainer;
    private ImageView cubeImageViewResearchLogo;
    private TextView textViewResearchItemRecordCount;
    private TextView textViewResearchTitle;

    private TextView textViewResearchContent;
    private android.widget.TextView textViewMobDetailSend;
    private ImageView imageViewMobDetailShare;

    private QDRefreshListView listView;
    private MobListAdapter mobListAdapter;

    //share
    private ShareDialog shareDialog;
    private ArticleInfoShare articleInfoShare;

    private boolean isLoadingMore;
    private boolean isHasMore;

    private int modId;
    private long lastLoadTime;
    private boolean isLastRespEmpty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voting_mob_details);

        this.articleMeta = getIntent().getParcelableExtra(KEY_REQUEST_VOTING_DETAILS);
        this.modId = getIntent().getIntExtra(KEY_REQUEST_MOB_ID, -1);
        {
            Uri mData = getIntent().getData();
            if (mData != null && mData.getHost() != null && mData.getHost().equals(getString(R.string.ias_type_mob))) {
                modId = Integer.valueOf(mData.getPath().replace("/", ""));
            }
        }
        if (articleMeta == null && modId == -1) {
            return;
        }
        if (articleMeta != null) {
            modId = articleMeta.getPost().getId();
        }
        isHasMore = true;
        initViewRes();
        requestMobDetail();
        requestMobOptions(0);
        ReadDAO.getInstance().read(modId, QDEnum.DetailEnum.MOB.value);
    }

    private void initViewRes() {
        this.viewTitleHeaderBar = (TitleBar) findViewById(R.id.viewTitleHeaderBar);
        viewTitleHeaderBar.getImageViewTitleBarLeft().setVisibility(View.GONE);

        this.headerView = LayoutInflater.from(this).inflate(R.layout.view_research_listview_item, null);
        this.relativeLayoutResearchListViewItemContainer = (RelativeLayout) headerView.findViewById(R.id.relativeLayoutResearchListViewItemContainer);
        this.cubeImageViewResearchLogo = (ImageView) headerView.findViewById(R.id.cubeImageViewResearchLogo);
        this.textViewResearchItemRecordCount = (TextView) headerView.findViewById(R.id.textViewResearchItemRecordCount);
        this.textViewResearchTitle = (TextView) headerView.findViewById(R.id.textViewResearchTitle);
        this.textViewResearchContent = (TextView) headerView.findViewById(R.id.textViewResearchContent);
        headerView.findViewById(R.id.cubeImageViewResearchCategory).setVisibility(View.GONE);

        ViewGroup.MarginLayoutParams vl = (ViewGroup.MarginLayoutParams) relativeLayoutResearchListViewItemContainer.getLayoutParams();
        vl.setMargins(0, 0, 0, 0);
        this.relativeLayoutResearchListViewItemContainer.setLayoutParams(vl);

        int defaultPadding = getResources().getDimensionPixelOffset(R.dimen.article_paddingLeft);
        textViewResearchTitle.setPadding(defaultPadding, 0, defaultPadding, 0);
        textViewResearchTitle.setTextColor(getResources().getColor(R.color.black));
        textViewResearchTitle.setTextSize(LocalDisplay.px2sp(getResources().getDimension(R.dimen.vote_detail_title_textSize)));
        textViewResearchTitle.setMaxLines(10);

        textViewResearchContent.setPadding(defaultPadding, 0, defaultPadding, 0);
        textViewResearchContent.setTextColor(getResources().getColor(R.color.vote_detail_content_textColor));
        textViewResearchContent.setTextSize(LocalDisplay.px2sp(getResources().getDimension(R.dimen.vote_detail_content_textSize)));
        textViewResearchContent.setMaxLines(100);

        this.textViewMobDetailSend = (TextView) findViewById(R.id.textViewMobDetailSend);
        this.textViewMobDetailSend.setOnClickListener(this);
        this.imageViewMobDetailShare = (ImageView) findViewById(R.id.imageViewMobDetailShare);
        this.imageViewMobDetailShare.setOnClickListener(this);
        findViewById(R.id.imageViewMobDetailClose).setOnClickListener(this);

        this.listView = (QDRefreshListView) findViewById(R.id.mob_listview);
        this.mobListAdapter = new MobListAdapter(this);
        mobListAdapter.setOnMobClickListener(this);
        this.listView.addHeaderView(headerView);
        this.listView.setAdapter(mobListAdapter);
        this.listView.setOnRefreshAndLoadMoreListener(this);

        this.shareDialog = new ShareDialog(this);

        //因为模板已经有些可以复用的信息，预加载待回调回来再更新。
        if (articleMeta != null)
            displayPreloadData(articleMeta);
    }

    private void loadMore() {
        if (mobOptionsEntity != null && isHasMore)
            requestMobOptions(mobOptionsEntity.getResponse().getOptions().getLast_time());
    }

    private void displayPreloadData(ArticleMeta articleMeta) {
        viewTitleHeaderBar.setTitle(articleMeta.getPost().getCategory().getTitle());
        textViewResearchItemRecordCount.setText("" + articleMeta.getPost().getRecord_count());
        ImageUtil.getInstance().displayImage(articleMeta.getPost().getImage(), cubeImageViewResearchLogo);
        textViewResearchTitle.setText("" + articleMeta.getPost().getTitle());
        textViewResearchContent.setText("" + articleMeta.getPost().getDescription());
    }

    private void requestMobDetail() {
        getRequestManager().requestMobDetail(modId);
    }

    private void requestMobOptions(long lastTime) {
        if (lastTime == 0) //表示重头来Load，把这些标志位改回来
            isHasMore = true;
        if (isLoadingMore)
            return;
        isLoadingMore = true;
        getRequestManager().requestMobOptions(modId, lastTime);
    }

    private void displayDetailsResponseData(QuestionDetailsEntity questionDetailsEntity) {
        //top show
        viewTitleHeaderBar.setTitle(questionDetailsEntity.getResponse().getPost().getCategory().getTitle());
        textViewResearchItemRecordCount.setText("" + questionDetailsEntity.getResponse().getPost().getRecord_count());
        ImageUtil.getInstance().displayImage(questionDetailsEntity.getResponse().getPost().getImage(), cubeImageViewResearchLogo);
        textViewResearchTitle.setText("" + questionDetailsEntity.getResponse().getPost().getTitle());
        textViewResearchContent.setText("" + questionDetailsEntity.getResponse().getPost().getDescription());
        articleInfoShare = questionDetailsEntity.getResponse().getShare();
    }

    @Override
    protected void onRequestCallBack(NetUtil.NetParams params, JsonData response) {
        super.onRequestCallBack(params, response);
        if (params instanceof NetConfigs.RequestMobDetail) {
            questionDetailsEntity = QDJsonUtil.Json2Object(response.toString(), QuestionDetailsEntity.class);
            if (questionDetailsEntity.getResponse() != null)
            {
                displayDetailsResponseData(questionDetailsEntity);
            }
            else
            {
                displayToast(questionDetailsEntity.getMeta() != null? questionDetailsEntity.getMeta().getMsg(): getText(R.string.article_error_toast).toString());
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
            }
        } else if (params instanceof NetConfigs.RequestMobOptions) {
            NetConfigs.RequestMobOptions requestMobOptions = (NetConfigs.RequestMobOptions) params;
            isLoadingMore = false;
            mobOptionsEntity = QDJsonUtil.Json2Object(response.toString(), MobOptionsEntity.class);
            if (mobOptionsEntity.getResponse() != null) {
                isHasMore = mobOptionsEntity.getResponse().getOptions().isHas_more();
                lastLoadTime = mobOptionsEntity.getResponse().getOptions().getLast_time();
                isLastRespEmpty = false;
                if (requestMobOptions.getmLastTime() == 0) {
                    mobListAdapter.addTop(mobOptionsEntity.getResponse().getOptions().getList());
                } else {
                    mobListAdapter.addBottom(mobOptionsEntity.getResponse().getOptions().getList());
                }
                onUIRefreshComplete();
            }
        } else if (params instanceof NetConfigs.RequestMobLiked) {
            NetConfigs.RequestMobLiked requestLikeIt = (NetConfigs.RequestMobLiked) params;

            LikeItEntity likeItEntity = QDJsonUtil.Json2Object(response.toString(), LikeItEntity.class);
            //toast
            this.displayToast(likeItEntity.getMeta().getMsg());
            if (likeItEntity.getResponse() != null) {
                PraiseDAO.getInstance().save(requestLikeIt.getOptionId(), requestLikeIt.getGenre(), QDEnum.COPEnum.OPTION.value);
                //update ui
                mobListAdapter.updatePraiseNumber(requestLikeIt.getOptionId(), likeItEntity.getResponse().getPraise_count());
            }
        }
    }

    @Override
    public void onRequestErrorCallBack(NetUtil.NetParams params, Object response) {
        if (params instanceof NetConfigs.RequestMobOptions) {
            isLoadingMore = false;
            QLog.d(QDTAG, "onRequestErrorCallBack");
            listView.hasMoreLoadData(true, true);
        }
        else  if (params instanceof NetConfigs.RequestMobDetail) {
            displayToast(getText(R.string.article_error_toast).toString());
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 1000);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.textViewMobDetailSend:
                if (!UserInformationManager.getInstance().isLogin()) {
                    Intent intent = new Intent();
                    intent.setClass(this, LoginActivity.class);
                    this.startActivity(intent);
                } else {
                    Intent intent = new Intent(this, MyOptionActivity.class);
                    intent.putExtra(MyOptionActivity.EXTRA_MY_OPINION, questionDetailsEntity.getResponse().getPost());
                    startActivity(intent);
                }
                break;
            case R.id.imageViewMobDetailShare:
                if (!shareDialog.isShowing()) {
                    shareDialog.show();
                } else {
                    shareDialog.dismiss();
                }
                shareDialog.setArticleInfoShare(articleInfoShare);
                break;
            case R.id.imageViewMobDetailClose:
                finish();
                break;
        }
    }

    @Override
    public void onClickOption(int optionId) {

    }

    @Override
    public void onClickPraise(int optionId) {
        boolean isPraise = PraiseDAO.getInstance().isPraise(optionId, QDEnum.COPEnum.OPTION.value);
        getRequestManager().requestMobLiked(optionId, isPraise ? 2 : 1);
    }

    @Subscribe
    public void receiverAddNewMobEvent(EventAddNewMob event) {
        if (event.getMobId() == questionDetailsEntity.getResponse().getPost().getId() && event.getOptions() != null) {
            listView.setSelection(0);
            mobListAdapter.addNew(event.getOptions());
        }
    }

    @Override
    public void onLoadMore() {
        if (isHasMore) {
            requestMobOptions(lastLoadTime);
        }
    }

    @Override
    public void onRefreshBegin() {

    }

    @Override
    public void onUIRefreshComplete() {
        listView.hasMoreLoadData(isLastRespEmpty, isHasMore);
    }
}
